<?php
/**
 * Created by PhpStorm.
 * User: 郑合达
 * Date: 2018/12/13
 * Time: 15:32
 */

namespace app\mobilewx\controller;;

use app\Admin\controller\Activity;
use app\Model\ActivityModel;
use app\Model\ActivityRebateModel;
use app\Model\ArticleModel;
use app\Model\DeliveryDocModel;
use app\Model\RebateLogModel;
use app\Model\UsersModel;
use app\Model\WithdrawalsModel;
use think\Controller;
use app\Model\OrderModel;
use app\Model\GoodsCollectModel;
use app\Model\CommentModel;
use app\Model\UserLeverModel;
use app\Model\CouponListModel;
use app\Model\OrderGoodsModel;
use app\Model\GoodsModel;
use app\Model\RegionModel;
use app\Model\ReturnGoods;
use app\Model\UserAddressModel;
use app\Model\RechargeModel;
use Common_util_pub;
use think\Cache;
use think\Db;

class User extends Common
{

    public $user_id = 0;
    public $user = array();
    public $session_id;

    /*
    * 初始化操作
    */
    public function _initialize()
    {
        parent::_initialize();
        $this->yanz();
        if (session('?user_wx')) {
            $publics=new Publics();
            $publics->upLevel(session('user_wx.user_id'));//用户信息缓存
            $user = session('user_wx');
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息

        }

        $order_status_coment = array(
            'WAITPAY' => '待付款 ', //订单查询状态 待支付
            'WAITSEND' => '待发货', //订单查询状态 待发货
            'WAITRECEIVE' => '待收货', //订单查询状态 待收货
            'WAITCCOMMENT' => '待评价', //订单查询状态 待评价
        );
        $this->assign('order_status_coment', $order_status_coment);
    }

    /*
     * 用户中心首页
     */
    public function index()
    {
        $order_count = OrderModel::where('user_id',$this->user_id)->count(); // 我的订单数
        $goods_collect_count =GoodsCollectModel::where('user_id',$this->user_id)->count(); // 我的商品收藏
        $comment_count = CommentModel::where('user_id', $this->user_id)->count();//  我的评论数
        $coupon_count = CouponListModel::where('uid',$this->user_id)->count(); // 我的优惠券数量
        $level = UserLeverModel::where('level_id',$this->user['level'])->find(); // 等级名称
        $this->assign('level', $level);
        $this->assign('order_count', $order_count);
        $this->assign('goods_collect_count', $goods_collect_count);
        $this->assign('comment_count', $comment_count);
        $this->assign('coupon_count', $coupon_count);
        return view('index');
    }


    /**
     * 订单列表
     */
    public function order_list()
    {
        $where['user_id']=$this->user_id;
        $page =input('page',1);
        $type =input('type','');
        //条件搜索
        if ($type == 'WAITPAY'){//待付款
            $where['pay_status']=0;
            $where['order_status']=0;
            $where['pay_code'] =['neq','cod'];
        }elseif ($type == 'WAITSEND'){//待发货
            $where['pay_status']=1;
            $where['shipping_status']=['neq',1];
            $where['order_status']=array('in','0,1');
        }elseif ($type == 'WAITRECEIVE'){//代收货
            $where['shipping_status']=1;
            $where['order_status']=1;
        }elseif ($type == 'WAITCCOMMENT'){//已完成
            $where['order_status']=4;
        }

        if ($type!='WAITSEND'){
            $order_list = OrderModel::field('*')->where($where)->order('order_id DESC')->page($page,10)->select()->toArray();
        }else{
            $order_list = OrderModel::field('*')->where($where)->where('pay_status = 1 or pay_code = "cod"')->order('order_id DESC')->page($page,10)->select()->toArray();
        }
        //获取订单商品
        foreach ($order_list as $k => $v) {
            $logic = new UsersLogic();
            $order_list[$k] = $logic->set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = OrderGoodsModel::alias('og')->field('og.*')
                ->field('g.original_img')
                ->join('tp_goods g','g.goods_id = og.goods_id')
                ->where('order_id','=',$v['order_id'])
                ->where('is_send','<>',3)//退货的排除
                ->select()->toArray();
            $order_list[$k]['goods_list'] = $data;
            //已发货的订单
            if ($v['shipping_status']==1){
                $delive= DeliveryDocModel::where('order_id',$v['order_id'])->find();
                $order_list[$k]['invoice_no']=$delive->invoice_no;
            }
            if (!$data){
                unset($order_list[$k]);
            }

        }
        $order_status = ["待支付", "待发货", "待收货", "待评价", "已取消", "已完成", "已作废"];
        $shipping_status=["未发货","已发货","已换货","已退货"];
        $pay_status =["未支付","已支付"];
        $this->assign('order_status', $order_status);
        $this->assign('shipping_status', $shipping_status);
        $this->assign('pay_status', $pay_status);
        $this->assign('lists', $order_list);
        $this->assign('active', 'order_list');
        $this->assign('type', $type);
        if (request()->isAjax()) {
           return view('mobile@user/ajax_order_list');
        }
       return view('mobile@user/order_list');
    }

   
    /*
     * 订单详情
     */
    public function order_detail()
    {
        $id = input('id');
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = Db('tp_order')->where($map)->find();
        $logic = new UsersLogic();
        $order_info =$logic->set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        if (!$order_info) {
            $this->error('没有获取到订单信息');
            exit;
        }
        //获取订单商品
         $data=OrderGoodsModel::alias('og')  ->field('og.*')
             ->join('tp_goods g','g.goods_id = og.goods_id')
             ->where('order_id','=',$order_info['order_id'])
             ->select()->toArray();

        $order_info['goods_list']=$data;

//        $region_list =$logic->get_region_list();//地区列表
        $site=$order_info['province'].','.$order_info['city'].','.$order_info['district'];
        $order_info['site']=RegionModel::where('id','in',$site)->column('name');//地址数据
//        $region_list =$logic->get_region_list();//用户地址
        $invoice_no = Db('tp_delivery_doc')->where("order_id = $id")->column('invoice_no');//发货单

        $order_info['invoice_no'] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = Db('tp_order_action')->where(array('order_id' => $id))->select();
        $order_status = ["待支付", "待发货", "待收货", "待评价", "已取消", "已完成", "已作废"];
        $shipping_status=["未发货","已发货","部分发货"];
        $pay_status =["未支付","已支付"];
        $this->assign('order_status', $order_status);
        $this->assign('shipping_status', $shipping_status);
        $this->assign('pay_status', $pay_status);
        $this->assign('order_info', $order_info);
        $this->assign('order_action', $order_action);
    return view('mobile@user/order_detail');
    }

    /*
     * 退/换货申请列表
     */
    public function order_list2()
    {
       //退换货申请表
       $data['return']= ReturnGoods::where('user_id',$this->user_id)->alias('rg')
            ->join('tp_order_goods og','rg.rec_id = og.rec_id')
            ->select();
//        dump($data['return']->toArray());die();
        return view('mobile@user/order_list2',$data);

    }
    /*
 * 取消订单
 */
    public function cancel_order()
    {
        $id = input('id');
        //检查是否有积分，余额支付
        $order = Db('tp_order')->where(array('order_id'=>$id,'user_id'=>$this->user_id))->find();
        //检查是否未支付订单 已支付联系客服处理退款
        if(empty($order))
            return retJson('', 201, '订单不存在！');
//        //检查是否未支付的订单
        if($order['pay_status'] > 0 || $order['order_status'] > 0)
            return retJson('', 201, '支付状态或订单状态不允许！');
        //获取记录表信息
        //$log = M('account_log')->where(array('order_id'=>$order_id))->find();
//        $logic = new UsersLogic();
//        //有余额支付的情况
//        if($order['user_money'] > 0 || $order['integral'] > 0){
//            $logic->accountLog($this->user_id,$order['user_money'],$order['integral'],"订单取消，退回{$order['user_money']}元,{$order['integral']}积分");
//        }
        $row = Db('tp_order')->where(array('order_id'=>$id,'user_id'=>$this->user_id))->delete();
        $data['order_id'] = $id;
        $data['action_user'] = $this->user_id;
        $data['action_note'] = '您取消了订单';
        $data['order_status'] = 3;
        $data['pay_status'] = $order['pay_status'];
        $data['shipping_status'] = $order['shipping_status'];
        $data['log_time'] = time();
        $data['status_desc'] = '用户取消订单';
        Db('tp_order_action')->insert($data);//订单操作记录

        if(!$row){
            return retJson('', 201, '删除失败！');
        }
        return retJson('', 200, '删除成功！');
    }



    /**
     * 我的留言页面
     * 留言数据处理
     */
    public function message_list()
    {
        $page =input('page');
        if (request()->isPost()) {
            if (!captcha_check(input('verify_code'), 'admin_login')) {
                return retJson('', 201, '验证码错误');
            }
            $data['msg_type'] =input('msg_type');
            $data['msg_title'] = input('msg_title');
            $data['msg_content'] =input('msg_content');
            $data['user_id'] = $this->user_id;
            $user = session('user_wx');
            $data['user_name'] = $user['nickname'];
            $data['msg_time'] = time();

            if (Db('tp_feedback')->insert($data)) {
                return retJson('', 200, '留言成功');

            } else {
                return retJson('', 202, '留言失败');
            }
        }
        $msg_type = array(0 => '留言', 1 => '投诉', 2 => '询问', 3 => '售后', 4 => '求购');
        $message = Db('tp_feedback')->where("user_id=" . $this->user_id)->page($page,3)->select();
        $this->assign('message', $message);
        $this->assign('msg_type', $msg_type);
        if (request()->isAjax()) {
            return view('mobile@user/ajax_message_list');
        }
        return view('mobile@user/message_list');
    }

    /***
     * 我的收藏
     */
    public function collect_list()
    {
        $page =input('page',1);
        $res = GoodsCollectModel::alias('c')->field('c.collect_id,c.add_time')
            ->field('g.goods_id,g.goods_name,g.shop_price,g.original_img')
            ->join('tp_goods g','g.goods_id = c.goods_id','INNER')
            ->where('c.user_id','=',$this->user_id)
            ->order('c.add_time DESC')
            ->page($page,5)
            ->select();
        $this->assign('goods_list', $res);

        if (request()->isAjax()) {
         return view('mobile@user/ajax_collect_list');
    }
     return view('mobile@user/collect_list');
    }

    /*
    *取消收藏
    */
    public function cancel_collect()
    {
        $collect_id = input('collect_id');
        $user_id = $this->user_id;
        $where['collect_id']= $collect_id;
        $where['user_id'] = $user_id;
        $res = GoodsCollectModel::where($where)->delete();
          if(!$res){
              return retJson('', 201, '删除失败！');
                }
           return retJson('', 200, '删除成功！');

    }

    /*
     * 评论晒单
     */
    public function comment()
    {
        $user_id = $this->user_id;
        $status = input('status',0);
        $page =input('page',1);
        $pages =$page-1;

        if($status == 1){
            //已评论
            $res = CommentModel::alias('c')->field('c.*')
                ->field('g.*')
                ->join('tp_order_goods g','c.goods_id = g.goods_id and c.order_id = g.order_id','inner')
                ->where('c.user_id','=',$user_id)
                ->order('c.add_time desc')
                ->page($page,3)
                ->select()->toArray();
        }elseif($status == 0){
            $where['o.user_id']=$user_id;//用户id
            $where['og.is_send']=['in','1,2'];//0未发货，1已发货，2已换货，3已退货
            $where['og.is_comment']=0;
            $where['o.order_status']=2;//订单状态0 => "取消确认",1 => "已确认",2 => "已收货",3 => "已取消",4 => "已完成", 5 => "已作废"
            $res = OrderGoodsModel::alias('og')->field('*')
                ->join('tp_order o','o.order_id = og.order_id','left')
                ->where($where)
                ->order('o.order_id desc')
                ->page($page,3)
                ->select()->toArray();
//            dump(OrderGoodsModel::getlastsql());
        }elseif($status == -1){
            $where['o.user_id']=$user_id;
            $where['og.is_send']=1;
            $where['og.is_comment']=0;
            $where['o.order_status']=2;
            $data = OrderGoodsModel::alias('og')->field('*')
                ->join('tp_order o','o.order_id = og.order_id','left')
                ->where($where)
                ->order('o.order_id desc')
                ->page($page,3)
                ->select()->toArray();

            $where1['o.user_id']=$user_id;
            $where1['og.is_send']=1;
            $where1['og.is_comment']=1;
            $where['o.order_status']=2;
            $datas = OrderGoodsModel::alias('og')->field('*')
                ->join('tp_order o','o.order_id = og.order_id','left')
                ->field('*')
                ->join('tp_comment c','c.order_id = o.order_id','left')
                ->where($where1)
                ->order('o.order_id desc')
                ->page($page,3)
                ->select()->toArray();
            $res=array_merge($data,$datas);
        }


        $this->assign('status',$status);
        $this->assign('comment_list',$res);
        if (request()->isAjax()) {
            return view('mobile@user/ajax_comment_list');
        }
        return view('mobile@user/comment');
    }


    /*
 *添加评论
 */
    public function add_comment()
    {
        if (request()->isPost()) {
            // 晒图片
            $files = request()->file('image');
            $url=[];//图片地址
            foreach($files as $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->validate(['size' => 3145728, 'ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'upload/comment');
                if ($info) {
                    // 成功上传后 获取上传信息
                    $names = str_replace("\\", "/", $info->getSaveName());//把反斜杠(\)替换成斜杠(/)
                    array_push($url, '/upload/comment/'.$names);

                } else {
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }
            //数据
            $img = implode(",", $url);
            $add['img']=$img;
            $user_info = session('user_wx');
            $add['goods_id'] = input('goods_id');
            $add['email'] = $user_info['email'];
            $hide_username = input('hide_username');
            if (empty($hide_username)) {
                $add['username'] = $user_info['nickname'];
            }
            $add['order_id'] = input('order_id');
            $add['service_rank'] = input('service_rank');
            $add['deliver_rank'] = input('deliver_rank');
            $add['goods_rank'] = input('goods_rank');
            $add['content'] = input('content');
            $add['add_time'] = time();
            $add['user_id'] = $this->user_id;
            //添加评论
            if(!$add['order_id'] || !$add['goods_id']){
                return retJson('',201,'非法操作');
            }
            //检查订单是否已完成
            $order = Db('tp_order')->where("order_id = {$add['order_id']} AND user_id = {$add['user_id']}")->find();
            if($order['order_status'] != 2){
                return retJson('',202,'该笔订单还未确认收货');
            }

            //检查是否已评论过
            $goods = Db('tp_comment')->where("order_id = {$add['order_id']} AND goods_id = {$add['goods_id']}")->find();
            if($goods){
                return retJson('',202,'您已经评论过该商品');
            }

            $row =CommentModel::create($add);
            if($row)
            {
                //更新订单商品表状态
                Db('tp_order_goods')->where(array('goods_id'=>$add['goods_id'],'order_id'=>$add['order_id']))->update(['is_comment'=>1]);
                Db('tp_goods')->where(array('goods_id'=>$add['goods_id']))->setInc('comment_count',1); // 评论数加一
                // 查看这个订单是否全部已经评论,如果全部评论了 修改整个订单评论状态
                $comment_count   = Db('tp_order_goods')->where("order_id ='{$add['order_id']}' and is_comment = 0")->where('is_send',1)->count();
                if($comment_count == 0) // 如果所有的商品都已经评价了 订单状态改成已评价
                {
                    Db('tp_order')->where("order_id ='{$add['order_id']}'")->update(['order_status'=>4]);
                }
                $ress=1;
                return retJson($ress,200,'评论成功');
            }
            return retJson('',200,'评论失败');
        }
        //评论页面
        $rec_id = input('rec_id');
       $order_goods = OrderGoodsModel::alias('og')->field('og.*')
        ->field('gi.image_url')
        ->join('tp_goods_images gi','gi.goods_id = og.goods_id')
        ->where('og.rec_id','=',$rec_id)
        ->find();
//        dump($order_goods->toArray());die();
        $this->assign('order_goods', $order_goods);
      return view('mobile@user/add_comment');
    }

    /**
     * 优惠券数据返回
     */
    public function coupon()
    {
        $type = input('type',0);
        $page = input('page',1);
        if ($type==0){// 未使用
            $where['l.order_id'] = 0;
            $where['c.use_end_time'] = ['>',time()];
        }
        if($type == 1){
            //已使用
            $where['l.order_id'] = ['>',0];
            $where['l.use_time'] = ['>',0];
        }
        if($type == 2){
            //已过期
            $where['c.use_end_time'] = ['<',time()];
        }
        $where['l.uid'] = $this->user_id;
        $logs =CouponListModel::alias('l')->field('l.*')
                ->field('c.name,c.money,c.use_end_time,c.condition')
                ->join('tp_coupon c','l.cid = c.id','LEFT')
            ->where($where)
            ->order('l.send_time DESC,l.use_time')
            ->page($page,5)
            ->select();
        $this->assign('coupon_list', $logs);
        $this->assign('type', $type);
        if (request()->isAjax()) {
            return view('mobile@user/ajax_coupon_list');

        }
     return view('mobile@user/coupon');
}

    /**
     * 确认收货
     */
    public function order_confirm()
    {
        $id = input('id', 0);
        $where=[
            'order_id'=>$id,
            'user_id'=>$this->user_id
        ];


        $order = Db('tp_order')->where($where)->find();
        if($order['order_status'] != 1)
            return retJson('',201,'该订单不能收货确认');

        $data['order_status'] = 2; // 已收货
        $data['confirm_time'] = time(); // 收货确认时间

        $logic = new UsersLogic();
        $row = OrderModel::where(array('order_id'=>$id))->update($data);
        setDatabaseDef($row,'收货失败');
//        $logic->order_give($order);// 调用送礼物方法, 给下单这个人赠送相应的礼物
        $set=['user_id'=>session('user_wx.first_leader')];

        //分销用户追加佣金
        $public=new Publics();
        $public->commission_send($id);//分销商佣金发放
        return retJson('',200,'收货成功');

    }

    /**
     * 计数购物车商品数量
     */
    public function header_cart_list()
    {
        $res =Db('tp_cart')->where('user_id',$this->user_id)->count('id');
        cookie('cn', $res, 3600);
    }

    /**
     * 申请退货/换货
     */
    public function return_goods()
    {
        $order_id = input('order_id', 0);
        $order_sn = input('order_sn', 0);
        $goods_id = input('goods_id', 0);
        $spec_key = input('spec_key');
        $rec_id =input('rec_id');

        if (request()->isPost()) {
            // 晒图片
            $files = request()->file('return_imgs');
            $url = [];//图片地址
            foreach ($files as $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->validate(['size' => 3145728, 'ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'upload/return_goods');
                if ($info) {
                    // 成功上传后 获取上传信息
                    $names = str_replace("\\", "/", $info->getSaveName());//把反斜杠(\)替换成斜杠(/)
                    array_push($url, '/upload/return_goods/' . $names);

                } else {
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }

            $img = implode(",", $url);
            $data['imgs'] = $img;
            $data['order_id'] = $order_id;

            $data['order_sn'] = $order_sn;
            $data['goods_id'] = $goods_id;
            $data['addtime'] = time();
            $data['user_id'] = $this->user_id;
            $data['type'] = input('type'); // 服务类型  退货 或者 换货
            $data['reason'] = input('reason'); // 问题描述
            $data['spec_key'] = input('spec_key'); // 商品规格
            $data['rec_id'] = input('rec_id');
            $add = Db('tp_return_goods')->insert($data);
            if($add){
                $wheress['order_id']=$order_id;
                $wheress['goods_id']=$goods_id;
                $wheress['rec_id']=input('rec_id');
                OrderGoodsModel::where($wheress)->update(['is_send'=>2]);
            }
            return retJson('', 200, '申请成功,客服第一时间会帮你处理');
        }

        $c = Db('tp_order')->where("order_id = $order_id and user_id = {$this->user_id}")->count();
        if ($c == 0) {
            return retJson('', 203, '非法操作');
        }

        $return_goods = Db('tp_return_goods')->where("order_id = $order_id and goods_id = $goods_id and spec_key = '$spec_key'")->find();
        if (!empty($return_goods)) {
            $rest = $return_goods['id'];
            return retJson($rest, 201, '已经提交过退货申请!');
        }
        $goods = Db('tp_goods')->where("goods_id = $goods_id")->find();
        $this->assign('rec_id', $rec_id);
        $this->assign('goods', $goods);
        $this->assign('order_id', $order_id);
        $this->assign('order_sn', $order_sn);
        $this->assign('goods_id', $goods_id);
        $this->assign('spec_key',$spec_key);
       return view('mobile@user/return_goods');
    }



    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * 获取用户的地址列表
     * Cache缓存省市县数据
     *
     * convert_arr_key 指定数组的某个字段作为下标
     */
    public function address_list(){
       $user_id = $this->user_id;
        $lists = UserAddressModel::field('*')
            ->where('user_id',$user_id)
            ->select();//获取用户的地址列表
        if (empty(Cache::get('region_list'))){
            $region_list = Db::name('tp_region')->select();
            $res = convert_arr_key($region_list,'id');
            Cache::set('region_list',$res);
        }
        $list =$lists->toArray();



        $this->assign('region_list',Cache::get('region_list'));
        $this->assign('list',$list);
        $this->assign('lists',$lists);
        return view('mobile@user/address_list');
    }

    /**
     * 添加、编辑地址页面
     */
    public function add_skip(){
        $getData=input('get.');
        $data=[];
        if (isset($getData['address_id'])){
            $address=UserAddressModel::find($getData['address_id']);//地址原本信息
            if ($address->user_id!=session('user_wx.user_id')){
                $this->error('非法操作');
            }
            $data['data']=$address;
        }
//        $this->assign('region_list',Cache::get('region_list'));

        return view('mobile@user/add_address',$data);

    }

    /*
   * 添加、修改地址
   */
    public function add_address(){
        $getData=input('post.');
        $user_id = $this->user_id;
        if (isset($getData['address_id'])){//编辑进
            $setDatabase=UserAddressModel::update($getData);
        }else{
            $c = UserAddressModel::where('user_id',$user_id)->count();
            if($c ==0){//第一个地址默认
                $getData['is_default']=1;
            }
            if ($c >=20){
                //返回
                return retJson('',201,'添加失败，最多只能添加20个收货地址');
            }
            $getData['user_id']=$user_id;
            $setDatabase=UserAddressModel::insert($getData);

        }
      return  setDatabase($setDatabase);
    }

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     *
     * 设置默认地址
     */
    public function set_default(){
        $address_id =input('id');
        $user_id = Db::name('tp_user_address')->field('user_id')->where('address_id',$address_id)->find();
        $res = Db::name('tp_user_address')->where('user_id',$user_id['user_id'])->where('is_default',1)->find();
        if ($res){
            Db::name('tp_user_address')->where('address_id',$res['address_id'])->update(['is_default'=>0]);
        }
        $row = Db::name('tp_user_address')->where('address_id',$address_id)->update(['is_default'=>1]);
        if(!$row){
            return retJson('',201,'操作失败');
        }else{
            $this->redirect('address_list');
//            return retJson('',200,'操作成功');
        }
    }

    /**
     * 删除地址
     */
    public function del_address(){
        $id = input('id');
        $address = UserAddressModel::field('*')->where('address_id',$id)->find();
        $row = Db::name('tp_user_address')->where('address_id',$id)->delete();

        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if ($row){
            if ($address['is_default'] == 1){
                $address2 =UserAddressModel::field('*')->where('user_id',$address['user_id'])->find();
                if ($address2){
                    UserAddressModel::update([
                        'is_default'=>1
                    ],['address_id'=>$address2['address_id']]);
                }
            }
            return retJson('',200,'删除地址成功');
        }else{
            return retJson('',201,'删除地址失败');
        }

    }

    /*
     * 三级联动
     * 根据传过来的父id和等级level打印子数据（市、县）
     */
    public function getRegion()
    {
        $postData=input('post.');
        $where=[
            'parent_id'=>$postData['parent_id'],//父id
            'level'=>$postData['level']//地区等级-》省市县区
        ];
        $getRegio= RegionModel::where($where)->select();
        $html='';
        if($getRegio){
            foreach($getRegio as $h){
                if($h['id'] == $postData['parent_id']){
                    $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
                }
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }

        echo $html;

    }



    /**
     * 退换货列表
     * convert_arr_key  将数据库中查出的列表以指定的 id 作为数组的键名
     */
    public function return_goods_list()
    {

        $user_id = $this->user_id;
        $list = ReturnGoods::field('*')
            ->where('user_id',$user_id)
            ->order('id desc')
            ->page(1,4)
            ->select();
        $arr2 = array();
        foreach($list as $key => $val){
            $arr2[] = $val['goods_id'];
        }
        if(!empty($arr2)){
            $goods = GoodsModel::field('goods_id,goods_name')
                ->where("goods_id in (".  implode(',',$arr2).")")
                ->select();
            $good = convert_arr_key($goods,'goods_id');
            $this->assign('good',$good);
        }

        $this->assign('list',$list);
        return view('mobile@user/return_goods_list');
    }
    /**
     * 退换货加载更多
     */
    public function ajaxGetMore()
    {
        $p = input('p');
        if ($p === 'undefined') {
            $p = 2;
        }
        $user_id = $this->user_id;
        $list = ReturnGoods::field('*')
            ->where('user_id', $user_id)
            ->order('id desc')
            ->page($p, 4)
            ->select();
        $arr2 = array();
        foreach ($list as $key => $val) {
            $arr2[] = $val['goods_id'];
        }
        if (!empty($arr2)) {
            $goods = GoodsModel::field('goods_id,goods_name')
                ->where("goods_id in (" . implode(',', $arr2) . ")")
                ->select();
            $good = convert_arr_key($goods, 'goods_id');
        }
        if ($list){
            $num = array();
            foreach ($list as $k=>$v){
                if ($v['status'] ==0){
                    $status ='待客服处理';
                }elseif ($v['status']==1){
                    $status='客服处理中';
                }elseif ($v['status']==2){
                    $status='已完成';
                }

                $data = '<table width="95%" border="1" cellspacing="0" cellpadding="0">';
                $data.='<tr><td>返修/退换货编号</td><td>';
                $data.=$v['id'].'</td></tr>';
                $data.='<tr><td>订单编号</td><td><a target="_blank" onclick="number('.$v['order_id'].')">'.$v['order_sn'].'</a></td></tr>';
                $data.='<tr><td>商品名称</td><td><a onclick="goods('.$v['goods_id'].')" target="_blank">'.$good[$v['goods_id']]['goods_name'].'</a></td></tr>';
                $data.='<tr><td>申请时间</td><td>'.date("Y-m-d",$v['addtime']).'</td></tr>';
                $data.='<tr><td>状态</td><td>'.$status.'</td></tr>';
                $data.='<tr><td class="check_but_thh" colspan="2"><div><a href="return_goods_info?id='.$v['id'].'">查看</a></div></td></tr></table>';
                $num[] = $data;
            }
        }
        return $num;
    }

    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id=input('id');
        $return_goods = ReturnGoods::field('*')->where('id',$id)->find();
        if ($return_goods['imgs']){
         $return_goods['imgs'] = explode(',',$return_goods['imgs']);
        }
        $goods = GoodsModel::field('*')->where('goods_id',$return_goods['goods_id'])->find();
        $this->assign('goods',$goods);
        $this->assign('return_goods',$return_goods);
        return view('mobile@user/return_goods_info');
    }

    /*
    * 账户资金
    */
    public function account(){
        $type =input('type',1);
        $page =input('page',1);
        $user_id = $this->user_id;
        $user = Db::name('tp_users')
            ->where('user_id',$user_id)
            ->find();
        $res=[];
        if ($type==2){
            $res = Db::name('tp_account_log')
                ->where('user_id',$user_id)
                ->where('user_type',0)
                ->order('log_id desc')
                ->page($page,10)
                ->select();
        } elseif ($type==3){
            $res=RechargeModel::field('*')->where('user_id','=',$user_id)->order('order_id desc')->page($page,10)->select();
        }elseif($type==1){
            //消费记录
            $info1 = Db::name('tp_account_log')
                ->where('user_id',$user_id)
                ->where('user_type',0)
                ->order('log_id desc')
                ->page($page,10)
                ->select();
            //充值记录
            $info2=RechargeModel::field('*')->where('user_id','=',$user_id)->order('order_id desc')->page($page,10)->select()->toArray();

             $res=array_merge($info1,$info2);
            array_multisort(array_column($res,'change_time'),SORT_DESC,$res);
        }
        $this->assign('user',$user);
        $this->assign('res',$res);
        $this->assign('type',$type);
        if (request()->isAjax()) {
            return view('mobile@user/ajax_account_list');
        }
        return view('mobile@user/account');
    }

    /**
     * 充值页面
     * @return \think\response\View
     *
     */
    public function recharge(){
        $user_id = $this->user_id;
        $user =UsersModel::field('user_money,nickname')->where('user_id','=',$user_id)->find();
        $getActivity=$this->activity();//检查今天活动
        $this->assign('activity',$getActivity);
        $this->assign('user',$user);
        return view('recharge');
    }

    /**
     * 判断支付方式，完成支付
     * @return \think\response\Json
     */
    public function getPay(){
        $data = input('post.');
        if ($data['account']){
            $data['account']=$data['account']; //选择金额
        }else{
            $data['account']=$data['input_val'];//输入金额
        }
        $data['pay_code']=input('pay_radio');
        $data['user_id']=$this->user_id;
        $data['ctime']=time(); //充值时间
        $data['pay_status']=0; //待支付
        //生成订单号
        $ras= rand('100000','999999');//随机生成六位数
        $data['order_sn']=time().$ras;
        unset($data['input_val']);
        switch ($data['pay_radio']){
            case 'weixin':
                $data['pay_name']='微信支付';
                $this->diangdan($data); //添加订单记录
                $parameters= $this->wxpay($data['order_sn'],$data['account'],session('user_wx.openid'));
                return retJson($parameters,200,'充值成功');
            case 'alipayMobile':
                $data['pay_name']='支付宝支付';
                break;
            case 'unionpay':
                $data['pay_name']='银联支付';
                break;
        }


    }
    //添加充值记录
    public function diangdan($data){
        unset($data['pay_radio']);
        $res=RechargeModel::create($data);
    }


    /**
     * 调用微信H5支付
     * @param $order_sn  订单号
     * @param $money     金额
     * @param $openid     用户标识
     * @return $url      支付跳转地址
     */
    public function wxpay($order_sn,$money,$openid)
    {
        import('WxPayHelper', EXTEND_PATH . 'Wxpaym');
        $jsApi = new Common_util_pub();
        $parameters = $jsApi->getUrl3($order_sn,$money,$openid);
        return $parameters;
    }
//    //支付
//    public function getPay(){
//       $ras= rand('100000','999999');//随机生成六位数
//        $data['user_id']=$this->user_id;
//        $data['nickname']=input('nickname');
//        if (input('account')){
//            $data['account']=input('account');
//        }else{
//            $data['account']=input('input_val');
//        }
//        $data['ctime']=time();
//        $data['pay_time']=time();
//        $data['pay_code']=input('pay_radio');
//        $data['order_sn']=input('pay_radio').$ras;
//        $data['pay_status']=1;
//        $data['change_time']=time();
//        switch (input('pay_radio')){
//            case 'weixin':
//                $data['pay_name']='微信支付';
//                break;
//            case 'alipayMobile':
//                $data['pay_name']='支付宝支付';
//                break;
//            case 'unionpay':
//                $data['pay_name']='银联支付';
//                break;
//        }
//
//
//        $res=RechargeModel::create($data);
//
//        if($res){
//            $getActivity=$this->activity();//检查今天活动
//
//            $rebate=0;//返利
//            if (isset($getActivity['rebate'])){
//                foreach ($getActivity['rebate'] as $k=>$v){
//                    if ($v->recharge<=$data['account']){
//                        $rebate=$v->rebate;//返利
//                        break;
//                    }
//                }
//            }
//
//            $data['account']+=$rebate;
//            UsersModel::where('user_id',$this->user_id)->setInc('user_money', $data['account']);
//            return retJson('',200,'充值成功');
//        }
//            return retJson('',201,'充值失败');
//    }
    /*
     * 充值返利活动
     * 返回活动和返利
     */
    public function activity()
    {
        //检查今天活动
        $where=[
            'display'=>0,
            'start_time'=>['<=',time()],
            'end_time'=>['>=',time()]];
        $getActivity=ActivityModel::where($where)->order('id','desc')->find();
        if ($getActivity){
            $getActivity['rebate']=ActivityRebateModel::where('id','in',$getActivity->rebate_id)->order('recharge','desc')->select();
            $this->assign('activity',$getActivity);
        }
        return $getActivity;
    }


    /**
     * 修改密码
     */
    public function changepwd(){

        if (input('mobile') == ''){
            return retJson('', 201, '请输入手机号！');
        }
        if (strlen(input('mobile')) != 11 ){
            return retJson('', 201, '请输入正确的手机号！');
        }
        if (input('mobile_code') == ''){
            return retJson('', 201, '请输入验证码！');
        }
        if (input('password') == ''){
            return retJson('', 201, '请输入新密码！');
        }
        if (input('newpass') == ''){
            return retJson('', 201, '请确认密码！');
        }
        if (input('password') != input('newpass')){
            return retJson('', 201, '两次密码不相同！');
        }
        if (session(input('mobile')) == ''){
            return retJson('', 201, '该号码未获取验证码,请检查号码是否正确或重新获取验证码！');
        };

        if (input('mobile_code') != session(input('mobile'))['code']){
            return retJson('', 201, '验证码错误！');
        }
       $res = UsersModel::update([
          'password'=>md5(md5(input('password')))
       ],['mobile'=>input('mobile')]);

        if(!$res){
            return retJson('', 201, '修改失败！');
        }
        session(input('mobile'),null);

        return retJson('', 200, '修改成功！');
    }


    /**
     * 申请提现记录
     */
    public function withdrawals(){
        $this->yanz();
        $page =input('page',1);
        $data['commission']=$commission=session('user_wx.commission');// 我的佣金
        if(request()->isPost())
        {
//            if (!captcha_check(input('verify_code'), 'withdrawals')) {
//                return retJson('', 201, '验证码错误');
//            }
            $data = input('post.');
            unset($data['verify_code']);
            $data['user_id'] = $this->user_id;
            $data['create_time'] = time();
            $distribut_min = 100; // 最少提现额度
            if($data['money'] < $distribut_min)
            {
                return retJson('', 201, '每次最少提现额度'.$distribut_min);
            }
            if($data['money'] > $commission)
            {
                return retJson('', 201, "你最多可提现{$commission}账户余额.");
            }
            $info=WithdrawalsModel::insert($data);
            if($info){
                return retJson('', 200, '已提交申请,一天内受理');
            }else{
                return retJson('', 200, '提交失败,联系客服!');
            }
        }
        $data['list']=$list = WithdrawalsModel::where('user_id','=',$this->user_id)->order("id desc")->page($page,10)->select();
        $data['level_name']=$level_name = UserLeverModel::where('level_id',$this->user['level'])->find(); // 等级名称
        //佣金明细记录
       $data['rebate_log']=$rebate_log= RebateLogModel::where('user_id',session('user_wx.user_id'))->select()->toArray();
//       dump($rebate_log);
       if(request()->isAjax())
        {
            $this->display('ajaxx_withdrawals_list');
            exit;
        }
     return view('mobile@user/withdrawals',$data);
    }
}